/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.sound.filter;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class EchoFilter extends SoundFilter {

    private final short[] delayBuffer;
    private final float   decay;
    private int   delayBufferPos;

    public EchoFilter(int numDelaySamples, float decay) {
        this.delayBuffer = new short[numDelaySamples];
        this.delayBufferPos = 0;
        this.decay = decay;
    }

    @Override
    public int getRemainingSize() {
        float finalDecay = 0.01f;
        // derived from math.pow(decay,x) <= finalDecay
        int numRemainingBuffers = (int)
                Math.ceil(Math.log(finalDecay)/Math.log(decay));
        int bufferSize = delayBuffer.length *2;
        return bufferSize * numRemainingBuffers;
    }
    
    @Override
    public void reset() {
        for(int i=0;i<delayBuffer.length;i++) {
            delayBuffer[i] = 0;
        }
        delayBufferPos = 0;
    }
    
    @Override
    public void filter(byte[] buffer, int offset, int lenght) {
        for(int i=offset;i<offset+lenght;i+=2) {
            // --- update the sample...
            short oldSample = getSample(buffer, i);
            short newSample = (short)(oldSample+decay*delayBuffer[delayBufferPos]);
            setSample(buffer, i, newSample);
            
            // --- update the delay buffer...
            delayBuffer[delayBufferPos] = newSample;
            delayBufferPos++;
            if( delayBufferPos == delayBuffer.length ) {
                delayBufferPos = 0;
            }
        }
    }
    
}
